import React, { FC, ReactElement, useMemo, useEffect } from 'react';
import dayjs from 'dayjs';
import { Table, Tag, Popover, Image, Button, Modal, Popconfirm } from '@douyinfe/semi-ui';
import type { ColumnProps } from '@douyinfe/semi-ui/lib/es/table';
import { useCityStoreProvide } from '@/store';
import { KeywordSearch } from '@/components';
import ItemDetail from './sub/ItemDetail';
import ItemOperate from './sub/ItemOperate';
import type { FieldsCityInfo } from './types';
import { useFieldsCityList, useCurrentRow } from './hooks';

import './List.scss';

const FieldsCitiesListPage: FC = (): ReactElement => {
  const {
    tableLoading,
    tableData,
    total,
    page,
    pageSize,
    keyword,

    refresh,
    getList,
    setPage,
    setLoading,
    handleKeywordChange,
    handlePageInfoChange,
  } = useFieldsCityList();
  const {
    createModalVisible,
    detailModalVisible,
    editModalVisible,
    modalLoading,
    currentRow,

    handleEditCityInfo,
    handleAddCityInfo,
    handleCloseModal,
    handleDetailClick,
    handleEditClick,
    handleCreateClick,
    handleRemoveClick,
  } = useCurrentRow({ refresh, setLoading });
  const { refreshAllCities } = useCityStoreProvide();

  const tableColumns: Array<ColumnProps<FieldsCityInfo>> = useMemo(() => {
    return [
      {
        title: '城市简称',
        dataIndex: 'name',
        width: 120,
        fixed: 'left',
        render: (t: string) => {
          return <Tag color="cyan">{t}</Tag>;
        }
      },
      {
        title: '城市全称',
        dataIndex: 'aliasName',
        width: 150,
      },
      {
        title: '城市封面',
        dataIndex: 'img',
        width: 300,
        render: (t: string) => {
          if (!t?.length) return '-';
          return <Image src={t} width={200} height={100} />;
        }
      },
      {
        title: '城市描述',
        dataIndex: 'description',
        width: 180,
        render: (t?: string) => {
          if (!t?.length) return '-';
          if (t.length > 8) {
            return (
              <Popover
                showArrow
                style={{ maxWidth: 300 }}
                position="rightTop"
                content={(
                  <pre
                    style={{
                      padding: 8,
                      boxSizing: 'border-box',
                      whiteSpace: 'pre-wrap',
                    }}
                  >{t}</pre>
                )}
              >
                <span>{t.slice(0, 8)}...</span>
              </Popover>
            );
          }
          return t;
        }
      },
      {
        title: '创建时间',
        dataIndex: 'createTime',
        width: 220,
        render: (t?: Date) => {
          if (([undefined, null]).includes(t)) {
            return '-';
          }
          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '更新时间',
        dataIndex: 'updateTime',
        width: 220,
        render: (t?: Date) => {
          if (([undefined, null]).includes(t)) {
            return '-';
          }
          return dayjs(t).format('YYYY-MM-DD HH:mm:ss');
        }
      },
      {
        title: '操作',
        dataIndex: 'action',
        width: 300,
        fixed: 'right',
        render: (t: string, row: FieldsCityInfo) => {
          return (
            <div className="action-group">
              <Button theme="solid" type="secondary" onClick={() => handleDetailClick(row)}>
                查看详情
              </Button>
              <Button type="primary" theme="solid" onClick={() => handleEditClick(row)}>
                编辑内容
              </Button>
              <Popconfirm
                title="刪除"
                content="确认刪除該城市信息？"
                onConfirm={() => handleRemoveClick(row)}
              >
                <Button type="danger" theme="solid">
                  删除内容
                </Button>
              </Popconfirm>
            </div>
          );
        }
      },
    ];
  }, [handleDetailClick, handleEditClick, handleRemoveClick]);

  useEffect(() => {
    if (Array.isArray(tableData)) {
      refreshAllCities(); // 刷新城市信息
    }
  }, [tableData]);

  function handleSearch() {
    setPage(1);
    getList(1, pageSize, keyword);
  }

  return (
    <div className="container-full fields-cities-list-page">
      <KeywordSearch
        placeholder="请输入城市关键词（编码，全称）"
        loading={tableLoading}
        keyword={keyword}
        handleKeywordChange={handleKeywordChange}
        handleSearch={handleSearch}
      >
        <Button
          theme="solid"
          type="primary"
          onClick={handleCreateClick}
        >
          新建
        </Button>
      </KeywordSearch>
      <main className="main-content">
        <Table
          loading={tableLoading}
          dataSource={tableData}
          columns={tableColumns}
          scroll={{ x: '100%' }}
          pagination={{
            currentPage: page,
            pageSize: pageSize,
            total,
            showSizeChanger: true,
            onChange: handlePageInfoChange,
          }}
        />
      </main>
      {/* 创建内容的表单 */}
      <Modal
        title="创建新城市信息"
        visible={createModalVisible}
        width={960}
        onCancel={handleCloseModal}
        maskClosable={false}
        footer={<></>}
      >
        <ItemOperate
          type="add"
          loading={modalLoading}
          data={currentRow}
          onCancel={handleCloseModal}
          onSubmit={handleAddCityInfo}
        />
      </Modal>
      {/* 编辑内容的表单 */}
      <Modal
        title="编辑新城市信息"
        visible={editModalVisible}
        width={960}
        onCancel={handleCloseModal}
        maskClosable={false}
        footer={<></>}
      >
        <ItemOperate
          type="edit"
          loading={modalLoading}
          data={currentRow}
          onCancel={handleCloseModal}
          onSubmit={handleEditCityInfo}
        />
      </Modal>
      {/* 详情内容的表单 */}
      <Modal
        title="查看城市信息"
        visible={detailModalVisible}
        width={960}
        onCancel={handleCloseModal}
        maskClosable={false}
        footer={<></>}
      >
        <ItemDetail loading={modalLoading} data={currentRow} />
      </Modal>
    </div>
  );
}

export default FieldsCitiesListPage;